/*
 * @Author: 曹哈哈 2273766442@qq.com
 * @Date: 2024-08-28 13:50:58
 * @LastEditors: 曹哈哈 2273766442@qq.com
 * @LastEditTime: 2024-08-30 16:20:43
 * @FilePath: \riddle-uniapp\src\sheep\store\dict.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { defineStore } from "pinia";
import { clone, cloneDeep } from "lodash";
import DictAPi from "@/cfsheep/api/cfDict";
import {DICT_LIST} from '@/utils/dict'
const dictInfo = { 
    // 处理 DICT_LIST
    ...DICT_LIST.reduce((acc, { type, data }) => {
        acc[type] = data.reduce((dictAcc, item) => {
            dictAcc[item.value] = item; // 将对象属性赋值
            return dictAcc;
        }, {});
        return acc;
    }, {})
};
// 默认字典信息
const defaultDictInfo = {
  id: undefined, // id
  label: undefined, //
  value: undefined, 
};
const dict = defineStore({
  id: "dict",
  state: () => ({
    dict: clone(dictInfo),
    label: clone(dictInfo),
    lastUpdateTime: 0, // 上次更新时间//  字典信息
  }),

  actions: {
    async init() {
      this.getDictInfo()
      console.log('this.dict=>',this.dict.BILLING_METHODS)
      console.log('this.label=>',this.label.BILLING_METHODS['hourly'])
    },
    // 获取远程字典信息
    async getRemoteDictInfo(names) {
      if (names === undefined || names === null) {
        throw new Error("need Dict names");
      }
      const ps = [];
      names.forEach((n) => {
        this.dict[n] = {};
        this.label[n] = {};
        this[n] = [];

        ps.push(
          DictAPi.getDictTypeDetail({ type: n }).then((res) => {
			   // res.data = 
            let result = res.data.map((obj) => {
              return {
                ...obj, // 复制原对象的属性
              };
            });
            this.dict[n] = result;
            result.forEach((d) => {
              // 将对象属性赋值，Vue 3会自动追踪变化
              this.dict[n][d.value] = d;
              this.label[n][d.value] = d.label;
            });
          })
        );
      }); 
      await Promise.all(ps);
    },
	// 获取远程字典信息
	async getDictInfo() {
               // 初始化字典和标签
            this.dict = {};
            this.label = {};
            
            if (DICT_LIST) {
                DICT_LIST.forEach(item => {
                    this.dict[item.type] = item.data; // 将对象属性赋值
                    this.label[item.type] = {};
					item.data.forEach(data=>{
						   this.label[item.type][data.value] = data.label; // label 对应 value
					})
                 
                });
            }
    },

    // 更新字典相关信息 (手动限流，5 秒之内不刷新)
    async updateUserData() {
      // 防抖，5 秒之内不刷新
      const nowTime = new Date().getTime();
      if (this.lastUpdateTime + 5000 > nowTime) {
        return;
      }
      this.lastUpdateTime = nowTime;

      // 获取最新信息
      await this.init();
      return this.dict;
    },
  },
  persist: {
    enabled: true,
    strategies: [
      {
        key: "dict-store",
      },
    ],
  },
});

export default dict;
